# from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
# import faiss
# import numpy as np
from fastapi import FastAPI, Query
from pydantic import BaseModel
# from sentence_transformers import SentenceTransformer
from typing import Optional
# import httpx
from fastapi import Body
from tipsz8 import loadLocalData,saveLocalData
from difflib import SequenceMatcher
# 将 "text" 列转化为列表
# from pydantic import BaseModel
import json
# import os
# import sys
# sys.path.append(os.path.abspath("."))  # 添加项目根目录到模块搜索路径               
from knownledge.text_rerank import search_rerank
app = FastAPI()

mcp = FastApiMCP(
app,
name="My API MCP",
# base_url="http://localhost:8000",
description="My API description",
)



@app.get("/items/")
async def read_items():
    return [{"item_id": "Foo"}]

@app.get("/searchshop")
async def read_items(query: Optional[str] = Query(None, description="搜索关键词")):
    print(query)
    # async with httpx.AsyncClient() as client:
    #     response = await client.get("https://xsooy-weapp.zaojiai.com/api/warehouse?size=30")
    #     data = response.json()
        
    return data["data"]

@app.get("/gettags")
async def read_items(query: Optional[str] = Query(None, description="userID")):
    userTag = loadLocalData("./../user.json") or {}
    
    # async with httpx.AsyncClient() as client:
    #     response = await client.get("https://xsooy-weapp.zaojiai.com/api/warehouse?size=30")
    #     data = response.json()
    if query not in userTag:
        return ""
    return userTag[query]

class TagRequest(BaseModel):
    userId: str
    tagtxt: str

@app.post("/savetag")
async def read_items(request: TagRequest):
    # Accept userId and tagtxt as parameters
    userId = request.userId
    tagtxt = request.tagtxt

    if not userId or not tagtxt:
        return {"error": "userId and tagtxt are required"}

    # Save the tagtxt for the given userId
    userTag = loadLocalData("./../user.json") or {}
    userTag[userId] = tagtxt

    # Save the updated tags back to the file
    
    saveLocalData(userTag, "./../user.json")
    # async with httpx.AsyncClient() as client:
    #     response = await client.get("https://xsooy-weapp.zaojiai.com/api/warehouse?size=30")
    #     data = response.json()
        
    return  {"status": "success"}
class SortRequest(BaseModel):
    shoplist: object
    p: str
@app.post("/sortShop")
async def read_items(request: SortRequest):
    # Accept userId and tagtxt as parameters

    slist = request.shoplist
    slist = eval(slist)
    # slist = json.loads(slist)
    tem = {}
    if request.p:
        s,e = request.p.split("-")
        for i in slist.keys():
            if float(slist[i][0]) > float(s) and float(slist[i][0]) < float(e):
                tem[i] = slist[i]
                # print(f"符合价格区间：{slist[i]} {slist[i][0]} {s} {e}")
    else:
        tem = slist
    
    for i in list(tem.keys()):
    
        if i in tem:  
            product_name = tem[i][1]
            cpu_gpu_info = " ".join(product_name.split()[:3])
            # print(i)
            for j in list(tem.keys()):
                if i != j:
                    product_name_j = tem[j][1]
                    v= " ".join(product_name_j.split()[:3])
                    similarity = SequenceMatcher(None, v, cpu_gpu_info).ratio()
                    if similarity > 0.9:  # Similarity greater than 90%
                        # print(f"Removing product with high similarity ({similarity*10:.1f}/10): {v} {j} {cpu_gpu_info}")
                        del tem[j]
    str1 = []
    for i in list(tem.keys()):
        str1.append(i) 
    
    str1 = ",".join(str1)
    
        
    return  str1

class SearchkvRequest(BaseModel):
    price: str
    useplan: str
    cpu: str
    gpu: str
    question: str

@app.post("/searchkv")
async def read_items(request: SearchkvRequest):
    result = search_rerank(request)
    print(result)
    result_str = ",".join(map(str, result))
    return result_str


def use_route_names_as_operation_ids(app: FastAPI) -> None:
    """
    Simplify operation IDs so that generated API clients have simpler function
    names.

    Should be called only after all routes have been added.
    """
    for route in app.routes:
        if isinstance(route, APIRoute):
            route.operation_id = route.name 
            
mcp.mount()

if __name__ == '__main__':
    import uvicorn


    uvicorn.run(app, host="0.0.0.0", port=5000)